package com.example.meservice.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.UUID;

/**
 * 阿里云OSS对象存储工具类
 * 提供文件上传和删除功能，用于头像等静态资源管理
 *
 * @author czwa
 */
@Component
public class OssUtils {
    // OSS服务Endpoint（北京区域）
    public static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 凭证提供器（从环境变量获取AccessKey）
    public static final EnvironmentVariableCredentialsProvider credentialsProvider;

    // 静态代码块初始化凭证提供器
    static {
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            throw new RuntimeException("OSS凭证初始化失败", e);
        }
    }

    // 存储空间名称和区域
    public static final String bucketName = "wacoffee";
    public static final String region = "cn-beijing";

    /**
     * 上传用户头像到OSS
     *
     * @param content 头像文件字节数组
     * @return 上传后的文件访问URL
     * @throws Exception 上传过程中发生的异常
     */
    public static String uploadAvatar(byte[] content) throws Exception {
        // 生成唯一文件名（格式：avatar/UUID.jpg）
        UUID uuid = UUID.randomUUID();
        String objectName = "avatar/" + uuid + ".jpg";

        // 配置OSS客户端（启用V4签名版本）
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        // 创建OSS客户端实例
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 上传文件到OSS
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
        } finally {
            // 确保客户端资源关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 构建并返回文件访问URL
        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
    }

    /**
     * 从OSS删除文件
     *
     * @param url 文件访问URL
     * @throws Exception 删除过程中发生的异常
     */
    public static void delete(String url) throws Exception {
        // 从URL中解析文件名
        URL fileUrl = new URL(url);
        String objectName = fileUrl.getPath().substring(1);

        // 配置OSS客户端（启用V4签名版本）
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        // 创建OSS客户端实例
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 删除OSS文件
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.err.println("OSS操作异常：请求已到达OSS但被拒绝");
            System.err.println("错误信息：" + oe.getErrorMessage());
            System.err.println("错误码：" + oe.getErrorCode());
        } catch (ClientException ce) {
            System.err.println("客户端异常：网络连接或配置错误");
            System.err.println("错误信息：" + ce.getMessage());
        } finally {
            // 确保客户端资源关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
